package com.pm.controller;

import com.pm.entity.Issue;
import com.pm.entity.User;
import com.pm.service.IssueService;
import com.pm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 问题管理控制器
 */
@RestController
@RequestMapping("/api/issues")
@CrossOrigin(origins = "*")
public class IssueController {
    
    @Autowired
    private IssueService issueService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 获取所有问题
     */
    @GetMapping
    public ResponseEntity<List<Issue>> getAllIssues() {
        List<Issue> issues = issueService.getAllIssues();
        return ResponseEntity.ok(issues);
    }
    
    /**
     * 根据ID获取问题
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getIssueById(@PathVariable String id) {
        try {
            Issue issue = issueService.findById(id);
            if (issue == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "问题不存在");
                return ResponseEntity.badRequest().body(error);
            }
            return ResponseEntity.ok(issue);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "获取问题信息失败");
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 创建问题
     */
    @PostMapping
    public ResponseEntity<?> createIssue(@RequestBody Issue issue, Authentication authentication) {
        try {
            // 设置问题报告者为当前用户
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            issue.setReporterId(currentUser.getId());
            
            Issue createdIssue = issueService.createIssue(issue);
            
            Map<String, Object> response = new HashMap<>();
            response.put("issue", createdIssue);
            response.put("message", "问题创建成功");
            
            return ResponseEntity.ok(response);
            
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 更新问题
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateIssue(@PathVariable String id, @RequestBody Issue issue, Authentication authentication) {
        try {
            // 检查权限：只有问题报告者或分配人可以更新问题
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            Issue existingIssue = issueService.findById(id);
            
            if (existingIssue == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "问题不存在");
                return ResponseEntity.badRequest().body(error);
            }
            
            boolean canUpdate = existingIssue.getReporterId().equals(currentUser.getId()) ||
                              (existingIssue.getAssigneeId() != null && existingIssue.getAssigneeId().equals(currentUser.getId()));
            
            if (!canUpdate) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "无权限修改此问题");
                return ResponseEntity.badRequest().body(error);
            }
            
            issue.setId(id);
            issue.setReporterId(existingIssue.getReporterId()); // 保持原报告者
            Issue updatedIssue = issueService.updateIssue(issue);
            
            Map<String, Object> response = new HashMap<>();
            response.put("issue", updatedIssue);
            response.put("message", "问题更新成功");
            
            return ResponseEntity.ok(response);
            
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 删除问题
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteIssue(@PathVariable String id, Authentication authentication) {
        try {
            // 检查权限：只有问题报告者可以删除问题
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            Issue existingIssue = issueService.findById(id);
            
            if (existingIssue == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "问题不存在");
                return ResponseEntity.badRequest().body(error);
            }
            
            if (!existingIssue.getReporterId().equals(currentUser.getId())) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "无权限删除此问题");
                return ResponseEntity.badRequest().body(error);
            }
            
            boolean deleted = issueService.deleteIssue(id);
            if (!deleted) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "删除问题失败");
                return ResponseEntity.badRequest().body(error);
            }
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "问题删除成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "删除问题失败");
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 根据项目ID获取问题
     */
    @GetMapping("/project/{projectId}")
    public ResponseEntity<List<Issue>> getIssuesByProjectId(@PathVariable String projectId) {
        List<Issue> issues = issueService.findByProjectId(projectId);
        return ResponseEntity.ok(issues);
    }
    
    /**
     * 获取分配给我的问题
     */
    @GetMapping("/assigned-to-me")
    public ResponseEntity<List<Issue>> getMyAssignedIssues(Authentication authentication) {
        String currentUsername = authentication.getName();
        User currentUser = userService.findByUsername(currentUsername);
        List<Issue> issues = issueService.findByAssigneeId(currentUser.getId());
        return ResponseEntity.ok(issues);
    }
    
    /**
     * 获取我报告的问题
     */
    @GetMapping("/reported-by-me")
    public ResponseEntity<List<Issue>> getMyReportedIssues(Authentication authentication) {
        String currentUsername = authentication.getName();
        User currentUser = userService.findByUsername(currentUsername);
        List<Issue> issues = issueService.findByReporterId(currentUser.getId());
        return ResponseEntity.ok(issues);
    }
    
    /**
     * 根据状态获取问题
     */
    @GetMapping("/status/{status}")
    public ResponseEntity<List<Issue>> getIssuesByStatus(@PathVariable String status) {
        List<Issue> issues = issueService.findByStatus(status);
        return ResponseEntity.ok(issues);
    }
    
    /**
     * 根据优先级获取问题
     */
    @GetMapping("/priority/{priority}")
    public ResponseEntity<List<Issue>> getIssuesByPriority(@PathVariable String priority) {
        List<Issue> issues = issueService.findByPriority(priority);
        return ResponseEntity.ok(issues);
    }
    
    /**
     * 更新问题状态
     */
    @PatchMapping("/{id}/status")
    public ResponseEntity<?> updateIssueStatus(@PathVariable String id, @RequestBody Map<String, String> request, Authentication authentication) {
        try {
            // 检查权限：问题报告者或分配人可以更新状态
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            Issue existingIssue = issueService.findById(id);
            
            if (existingIssue == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "问题不存在");
                return ResponseEntity.badRequest().body(error);
            }
            
            boolean canUpdate = existingIssue.getReporterId().equals(currentUser.getId()) ||
                              (existingIssue.getAssigneeId() != null && existingIssue.getAssigneeId().equals(currentUser.getId()));
            
            if (!canUpdate) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "无权限修改此问题状态");
                return ResponseEntity.badRequest().body(error);
            }
            
            String status = request.get("status");
            boolean updated = issueService.updateIssueStatus(id, status);
            
            if (!updated) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "更新问题状态失败");
                return ResponseEntity.badRequest().body(error);
            }
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "问题状态更新成功");
            
            return ResponseEntity.ok(response);
            
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 分配问题
     */
    @PatchMapping("/{id}/assign")
    public ResponseEntity<?> assignIssue(@PathVariable String id, @RequestBody Map<String, String> request, Authentication authentication) {
        try {
            // 检查权限：只有问题报告者可以分配问题
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            Issue existingIssue = issueService.findById(id);
            
            if (existingIssue == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "问题不存在");
                return ResponseEntity.badRequest().body(error);
            }
            
            if (!existingIssue.getReporterId().equals(currentUser.getId())) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "无权限分配此问题");
                return ResponseEntity.badRequest().body(error);
            }
            
            String assigneeId = request.get("assigneeId");
            boolean assigned = issueService.assignIssue(id, assigneeId);
            
            if (!assigned) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "分配问题失败");
                return ResponseEntity.badRequest().body(error);
            }
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "问题分配成功");
            
            return ResponseEntity.ok(response);
            
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 解决问题
     */
    @PatchMapping("/{id}/resolve")
    public ResponseEntity<?> resolveIssue(@PathVariable String id, Authentication authentication) {
        try {
            // 检查权限：问题分配人可以解决问题
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            Issue existingIssue = issueService.findById(id);
            
            if (existingIssue == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "问题不存在");
                return ResponseEntity.badRequest().body(error);
            }
            
            if (existingIssue.getAssigneeId() == null || !existingIssue.getAssigneeId().equals(currentUser.getId())) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "无权限解决此问题");
                return ResponseEntity.badRequest().body(error);
            }
            
            boolean resolved = issueService.resolveIssue(id);
            
            if (!resolved) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "解决问题失败");
                return ResponseEntity.badRequest().body(error);
            }
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "问题解决成功");
            
            return ResponseEntity.ok(response);
            
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
}